<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="this.userName"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="落款时间" prop="signatureTime">
        <el-date-picker clearable
          v-model="queryParams.signatureTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择落款时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable
          v-model="queryParams.uploadTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属阶段" prop="stage">
        <el-select v-model="queryParams.stage" placeholder="请选择所属阶段" clearable>
          <el-option v-for="dict in dict.type.party_develop_stage" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          :disabled="statusChecking"
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['system:files:manage']"
        >上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="statusChecking"
          type="warning"
          plain
          icon="el-icon-upload"
          @click="handleCheck"
          v-hasPermi="['system:files:manage']"
        >提交备案</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="filesList" >
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="用户ID" align="center" prop="userId" v-if="false"/>
      <el-table-column label="姓名" align="center" prop="userName" v-if="false"/>
      <el-table-column label="文件路径" align="center" prop="filePath" v-if="false"/>
      <el-table-column label="文件记录ID" align="center" prop="recordId" />
<!--      <el-table-column label="文件名" align="center" prop="fileName" />-->
      <el-table-column label="文件名" align="center" prop="fileName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <a @click="handleDownload(scope.row)" style="color:#1E90FF;cursor:pointer">{{ scope.row.fileName}}</a>
        </template>
      </el-table-column>
      <el-table-column label="落款时间" align="center" prop="signatureTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signatureTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="所属阶段" align="center" prop="stage" />-->
      <el-table-column label="所属阶段" align="center" prop="stage">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.party_develop_stage" :value="scope.row.stage" />
        </template>
      </el-table-column>
      <el-table-column label="备案状态" align="center" prop="checkStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.party_develop_check" :value="scope.row.checkStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:files:manage']"
            v-if="scope.row.checkStatus === 0 || scope.row.checkStatus === 2"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:files:manage']"
            v-if="scope.row.checkStatus === 0 || scope.row.checkStatus === 2"
          >删除</el-button>
          <el-col v-if="scope.row.checkStatus === 1">处理中</el-col>
          <el-col v-if="scope.row.checkStatus === 3">已备案</el-col>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改党员发展文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="文件记录ID" prop="recordId" v-if="false">
            <el-input v-model="form.recordId" :disabled="true"/>
          </el-form-item>
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="form.fileName" placeholder="请输入文件名" />
          </el-form-item>
          <el-form-item label="落款时间" prop="signatureTime">
            <el-date-picker clearable
                            v-model="form.signatureTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择落款时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="所属阶段" prop="stage">
<!--            <el-input v-model="form.stage" placeholder="请选择所属阶段" />-->
            <el-select v-model="form.stage" placeholder="请选择所属阶段">
<!--              <el-option v-for="dict in dict.type.party_develop_stage" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
              <el-option v-for="dict in filteredStages" :key="dict.label" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-col :span="24">
            <el-form-item label="选取文件" prop="fileList">
              <el-upload
                class="upload-demo"
                drag
                ref="newupload"
                :limit="1"
                :multiple="false"
                :action="upload.url"
                :headers="upload.headers"
                :on-success="handleFileSuccess"
                :file-list="upload.fileList"
                :on-remove="handleRemove"
                :on-progress="handleFileUploadProgress"
                :auto-upload="true">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFiles, getFiles, delFiles, addFiles, updateFiles,updateCheckStatus } from "@/api/system/files";
import { listDevelop, getDevelop, delDevelop, addDevelop, updateDevelop } from "@/api/system/develop";
import { getToken } from "@/utils/auth";

export default {
  name: "Files",
  dicts: ['user_party','party_develop_stage','party_develop_check'],
  data() {
    return {
      dict_local: {
        type: {
          party_develop_stage: [
            { value: 1, label: '申请人' },
            { value: 2, label: '申请人培养' },
            { value: 3, label: '积极分子' },
            { value: 4, label: '积极分子培养' },
            { value: 5, label: '发展对象' },
            { value: 6, label: '发展对象培养' },
            { value: 7, label: '预备党员' },
            { value: 8, label: '预备党员培养' },
            { value: 9, label: '党员' },
            { value: 10, label: '党员培养' }
          ]
        }
      },
      httpUrl : process.env.VUE_APP_BASE_API,
      //用户ID
      userId: null,
      //用户姓名
      userName: null,
      //用户党员身份阶段
      currentStage: null,
      //允许上传文件的阶段
      allowedValues: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 党员发展文件表格数据
      filesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        signatureTime: null,
        uploadTime: null,
        filePath: null,
        stage: null,
        checkStatus: null,
        userId:null
      },
      // 表单参数
      form: {},
      //上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: "文件名不能为空", trigger: "blur" },
          { min: 3, message: '文件名不能少于3个字', trigger: 'blur' }
        ],
        signatureTime: [
          { required: true, message: "落款时间不能为空", trigger: "blur" }
        ],
        stage: [
          { required: true, message: "所属阶段不能为空", trigger: "blur" }
        ],
        // fileList: [
        //   { required: true, message: "文件不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.userId = this.$route.params.userId;
    this.queryParams.userId = this.userId;
      this.getpartyList();
    this.getList();
  },
  computed: {
    filteredStages() {
      // 这里定义允许的 value 值
      // this.allowedValues = [2, 3];
      return this.dict_local.type.party_develop_stage.filter(item => this.allowedValues.includes(item.value));
    },
    statusChecking() {
      // 检查 filesList 中是否有任何项的 checkStatus 为 1
      return this.filesList.some(file => file.checkStatus === 1);
    }
  },
  methods: {
    /** 查询用户列表 */
    getpartyList() {
      listDevelop().then(response => {
        response.rows.forEach(row => {
          row.status = this.getCurrentStage(row);
          this.currentStage = row.status
        });
        response.rows.forEach(row => {
          if(row.userId == this.userId){
            this.userName = row.userName
            this.userId = row.userId
            //判断可上传阶段
            if(row.status == 0 || row.status == 5){
              this.allowedValues.push(Number(row.status)+1);
            }else if(row.status == 5){
              this.allowedValues.push(2*Number(row.status));
            }else {
              this.allowedValues.push(2*Number(row.status));
              this.allowedValues.push(2*Number(row.status)+1);
            }
          }
        });
      });
    },
    //判断当前所处阶段
    getCurrentStage(row) {
      for (let i = 5; i >= 1; i--) {
        const stageFlagField = `stage${i}Flag`;
        const stageFlag = row[stageFlagField];
        if (stageFlag === 1) {
          return `${i}`;
        }
      }
      return '0';
    },
    /** 查询党员发展文件列表 */
    getList() {
      this.loading = true;
      listFiles(this.queryParams).then(response => {
        this.filesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        fileName: null,
        signatureTime: null,
        uploadTime: null,
        filePath: null,
        stage: null,
        checkStatus: null,
      };
      this.upload.fileList = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.userId)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加党员发展文件";
    },
    //提交审核
    handleCheck(){
      if(this.filesList.length == 0){
        this.$message({
          message: '未上传任何文件',
          type: 'warning'
        });
        return;
      }
      //查询用户当前阶段,检索文件列表中是否存在对应必须文件
      var needfulFileList = []
      if(this.currentStage == 0){
        needfulFileList = ['1.1入党申请书.docx','1.2入党申请人谈话.pdf']
      }else if(this.currentStage == 1){
        needfulFileList = ['2.1.1 列入党积极分子党小组意见.docx','2.1.2 团组织推荐入党积极分子审核表.docx','2.1.3 召开支委会研究列为入党积极分子.docx']
      }else if(this.currentStage == 2){
        needfulFileList = ['3.1.1 团组织推荐党的发展对象审核表.doc','3.1.2拟为发展对象公示.doc','3.1.6确定发展对象党小组意见.doc','3.1.7确定发展对象支委会意见.doc']
      }else if(this.currentStage == 3){
        needfulFileList = ['4.1.2接收预备党员公示.doc','4.3.1接收预备党员支部党员大会决议.doc']
      }else if(this.currentStage == 4){
        needfulFileList = ['5.3.1转正申请.doc','5.3.2同预备期满党员谈话.doc','5.3.3预备党员联系人转正意见.doc','5.3.8预备党员按期转正支委会意见.doc']
      }else{
        needfulFileList = []
      }
      if(this.allNeedfulFiles(needfulFileList,this.filesList)){
        //提交审核,更改当前阶段文件状态
        const updateForm = {
          userId: this.userId,
          stages: this.allowedValues,
          checkStatus: 1
        };
        updateCheckStatus(updateForm).then(response => {
          this.$modal.msgSuccess("提交成功");
          this.getList();
        });
      }

      // this.$modal.confirm('确认要提交"' + this.userName + '"当前阶段的申请吗？').then(function() {
      //   //提交审核,更改当前阶段文件状态
      //   const updateForm = {
      //     userId: this.userId,
      //     stages: this.allowedValues,
      //     checkStatus: 1
      //   };
      //   console.log(updateForm)
      //   updateCheckStatus(updateForm).then(response => {
      //     console.log(response)
      //   });
      //   return 1;
      // }).then(() => {
      //   //提示请求成功，刷新
      //   this.$modal.msgSuccess("提交成功");
      //   this.getList();
      // }).catch(function() {
      //   // this.$modal.msgError("提交失败，请稍后重试")
      //   console.log("提交失败，请稍后重试")
      // });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const userId = row.userId || this.ids
      const recordId = row.recordId
      getFiles(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改党员发展文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.userId = this.userId
          // this.form.uploadTime = this.getFormattedDate()
          // this.form.filePath = this.upload.fileList[0].response.fileName
          // this.form.checkStatus = 0
          // addFiles(this.form).then(response => {
          //   this.$modal.msgSuccess("新增成功");
          //   this.open = false;
          //   this.getList();
          // });

          if (this.form.recordId != null) {
            updateFiles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.userId = this.userId
            this.form.uploadTime = this.getFormattedDate()
            this.form.filePath = this.upload.fileList[0].response.fileName
            this.form.checkStatus = 0
            addFiles(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除党员发展文件编号为"' + userIds + '"的数据项？').then(function() {
        return delFiles(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/files/export', {
        ...this.queryParams
      }, `files_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.upload.fileList = fileList;
      this.form.fileName = file.name;
      this.$modal.msgSuccess(response.msg);
    },
    handleRemove(file, fileList){
      this.upload.fileList = fileList;
    },
    handleDownload(row) {
      var url = this.httpUrl + row.filePath;
      var suffix = url.substring(url.lastIndexOf("."), url.length);

      function downloadFile(url, fileName) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.addEventListener('load', function () {
          if (xhr.status === 200) {
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhr.response);
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(a.href);
          }
        });
        xhr.addEventListener('progress', function (e) {
          let percent = Math.trunc(e.loaded / e.total * 100);
        })
        // 错误处理
        xhr.addEventListener('error', function (e) {
          // todo
        })
        // 发送请求
        xhr.send();
      }
      downloadFile(url, row.fileName);
    },

    getFormattedDate() {
      const now = new Date();
      // 获取年份
      const year = now.getFullYear();
      // 获取月份（注意：月份是从0开始的，所以需要加1）
      const month = String(now.getMonth() + 1).padStart(2, '0');
      // 获取日期
      const day = String(now.getDate()).padStart(2, '0');
      // 获取小时
      const hours = String(now.getHours()).padStart(2, '0');
      // 获取分钟
      const minutes = String(now.getMinutes()).padStart(2, '0');
      // 获取秒
      const seconds = String(now.getSeconds()).padStart(2, '0');
      // 格式化为 YYYY-MM-DD HH:mm:ss
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      return formattedDate;
    },

    //上传校验控制
    allNeedfulFiles(needfulFileList, filesList) {
      // 首先创建一个 Set 来存储 filesList 中所有的 fileName
      const fileNamesSet = new Set(filesList.map(file => file.fileName));
      // 用于记录缺失的文件名
      const missingFiles = [];
      // 遍历 needfulFileList，检查每个文件名是否在 fileNamesSet 中
      for (const needfulFileName of needfulFileList) {
        if (!fileNamesSet.has(needfulFileName)) {
          /// 如果 needfulFileList 中的文件名不在 filesList 中，则记录到 missingFiles 中
          missingFiles.push(needfulFileName);
        }
      }
      // 输出提示信息
      if (missingFiles.length > 0) {
        this.$notify({
          title: '缺少以下文件：',
          message: missingFiles.join(', '),
          type: 'warning',
          duration: 0
        });
        return false;
      } else {
        console.log('所有文件都存在。');
        return true; // 返回 true 表示所有文件都存在
      }
    }
  }
};
</script>
